package com.vcourse.service.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.vcourse.commons.result.R;
import com.vcourse.commons.result.ResultCodeEnum;
import com.vcourse.service.admin.service.IndexService;
import com.vcourse.service.admin.service.UserService;
import com.vcourse.service.admin.vo.AdminUserLoginParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zengsh123
 * @date 2020-06-17 18:36
 */

@RestController
@RequestMapping("/admin/index")
public class IndexController {
    @Resource
    private IndexService indexService;
    @Resource
    private UserService userService;

    @ApiOperation(value = "登录以后返回token")
    @PostMapping("login")
    public R login(@RequestBody AdminUserLoginParam loginParam) {
        String token = userService.login(loginParam.getUsername(), loginParam.getPassword());
        if (token == null) {
            return R.setResult(ResultCodeEnum.LOGIN_ERROR);
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return R.ok().data(tokenMap);
    }


    @PostMapping("logout")
    public R logout() {
        return R.ok();
    }

    /**
     * 根据token获取用户信息
     */
    @GetMapping("info")
    public R info(){
        //获取当前登录用户用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        Map<String, Object> userInfo = indexService.getUserInfo(username);
        return R.ok().data(userInfo);
    }

    /**
     * 获取菜单
     */
    @GetMapping("menu")
    public R getMenu(){
        //获取当前登录用户用户名
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        List<JSONObject> permissionList = indexService.getMenu(username);
        return R.ok().data(permissionList);
    }
}
